/*
 * DataBases 445 Library DBMS 
 */

package gui;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;

import dbConnection.Database;

/**
 * Class to create the gui for the Item Search Page for the
 * Administrative view. This includes the necessary front end, 
 * and back end code.
 * 
 * @author Prentice, Arslan, Herndon
 *
 */
@SuppressWarnings("serial")
public class AdminItemSearchResult extends JPanel {

	/** The inventory ID of the item. */ 
	public int inventoryID;

	/** The Database object for the class. */
	public Database DB;

	/**
	 * Initializes the Gui + Backend code for the ItemSearchResult 
	 * panel object.
	 * 
	 * @param inventoryID The inventory ID of the item
	 * @param DB A DataBase object
	 */
	public AdminItemSearchResult(final int inventoryID, Database DB) {
		this.inventoryID = inventoryID;
		this.DB = DB;

		setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
		final JTextArea summary = new JTextArea();
		summary.setText(getSummary());

		final JButton checkin = new JButton("Check In");
		boolean isCheckedOut = false;

		setMaximumSize(new Dimension(600,120));
		
		if(this.DB.con != null) {
			Statement statement = null;	  
			try {
				statement = this.DB.con.createStatement();

				ResultSet resultSet = statement.executeQuery("SELECT CheckoutStatus FROM " +
						"inventory WHERE InventoryId=" + this.inventoryID + ";");
				if (resultSet != null && resultSet.next() && !resultSet.getString(1).equals("Checked Out")) {
					isCheckedOut = true;
				}
			} catch (SQLException e) {
				// continue
			}


			checkin.setEnabled(!isCheckedOut);
			checkin.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					checkin.setEnabled(false);
				}
			});


			String[] conditions = {"Good","Fair","Poor"};
			final JComboBox<String> condition = new JComboBox<String>(conditions);
			condition.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if(AdminItemSearchResult.this.DB.con != null) {
						Statement statement = null;	  
						try {
							statement = AdminItemSearchResult.this.DB.con.createStatement();
							java.util.Date today = new java.util.Date();
							Date sqlToday = new java.sql.Date(today.getTime());
							statement.executeUpdate("UPDATE inventory SET Cond=" + condition.getSelectedItem().toString() +
									", ConditionLastChecked=" + sqlToday.toString() + " WHERE " + "InventoryId=" +
									AdminItemSearchResult.this.inventoryID + ";");
						/*	statement = AdminItemSearchResult.this.DB.con.createStatement();
							statement.executeQuery("UPDATE inventory SET ConditionLastChecked=" + sqlToday.toString() 
									+ " WHERE " + "InventoryId=" + AdminItemSearchResult.this.inventoryID + ";"); */
						} catch (SQLException ex) {
							// continue
						}

						summary.setText(getSummary());
					}
				}
			});

			final JButton remove = new JButton("Permanently Remove");
			remove.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if(AdminItemSearchResult.this.DB.con != null) {
						Statement statement = null;	  
						try {
							statement = AdminItemSearchResult.this.DB.con.createStatement();
							System.out.println("DELETE InventoryId FROM " +
								"inventory WHERE InventoryId=" + AdminItemSearchResult.this.inventoryID + ";");
							statement.executeUpdate("DELETE FROM " +
									"inventory WHERE InventoryId=" + AdminItemSearchResult.this.inventoryID + ";");
							//resultSet.updateString(1, condition.getSelectedItem().toString());
						} catch (SQLException ex) {
						    JOptionPane.showMessageDialog(AdminItemSearchResult.this,
							    "Error Deleting Inventory");
						}		
					}

					summary.setText("This item has been removed");
					checkin.setEnabled(false);
					condition.setEnabled(false);
					remove.setEnabled(false);

				}
			});
			add(summary);
			add(checkin);
			add(condition);
			add(remove);
		}
	}

	/**
	 * Accesses the database to get a summary of information on the item. Returns 
	 * the data in the form of a string.
	 * 
	 * @return A summary of the item from the database.
	 */
	public String getSummary() {
		//if connection is successfully established, create statement
		if(this.DB.con == null) return "Database is currently inaccesible";
		Statement statement = null;	  
		try {
			statement = this.DB.con.createStatement();
		} catch (SQLException e) {
			return "Unable to create statement";
		}

		ResultSet resultSet = null;
		if(statement != null) {
			try {
				resultSet = statement.executeQuery("SELECT item.ItemId,item.Title,item.Author,inventory.Cond,inventory.ConditionLastChecked," +
						"inventory.DueDate,inventory.UserId" +
						" FROM item NATURAL JOIN inventory WHERE " + 
						"inventory.InventoryId=" + AdminItemSearchResult.this.inventoryID + ";");
			} catch (SQLException e) {
				return "Unable to create statement";
			}
		}
		StringBuilder bd = new StringBuilder();
		//if resultset is received and is not empty,
		// iterate over resultset to get values
		try {
			if(resultSet != null && resultSet.next()) {
				bd.append("ItemId: " + resultSet.getString(1) + "\n");
				bd.append("Title: " + resultSet.getString(2) + "\n");
				bd.append("Author: " + resultSet.getString(3) + "\n");
				bd.append("Condition: " + resultSet.getString(4) + "\n");
				bd.append("Condition Last Checked: " + resultSet.getString(5) + "\n");
				bd.append("Checkout Due Date: " + resultSet.getString(6) + "\n");
				bd.append("Checked out by User#: " + resultSet.getString(7) + "\n");
				//				bd.append("Overdue Reminder Status: " + resultSet.getString(7) + "\n");
			}
		} catch (SQLException e) {
			System.out.println("Unable to iterate over resultset");
		}

		return bd.toString();
	}
}

